﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine.Sgml.Schema;

namespace Engine.Sgml.Test.Util {
    public class DtdSchemaGenerator {
        private DModelGroupsGenerator modelGroupsGenerator;
        private StringBuilder builder;

        public DtdSchemaGenerator() {
            modelGroupsGenerator = new DModelGroupsGenerator();
            builder = new StringBuilder();
            }

        public DtdSchema Generate(DModelGroupsConfiguration configuration) {
            configuration.ElementConfiguration.ElementNumber = 1;
            DModelGroups inclusions = null;
            DModelGroups model = modelGroupsGenerator.Generate(configuration);
            builder.Clear();
            builder.Append("<!ELEMENT");
            builder.Append(' ');
            builder.Append(configuration.ElementConfiguration.ElementName);
            builder.Append(' ');
            builder.Append(model.ToString());
            builder.Append(' ');
            if (configuration.GenerateInclusionElements) {
                inclusions = modelGroupsGenerator.GenerateInclusion(configuration);
                builder.Append('+');
                builder.Append(inclusions.ToString());
                }
            builder.Append('>');
            foreach (IModelGroupsItem item in model) {
                builder.AppendLine();
                builder.Append("<!ELEMENT");
                builder.Append(' ');
                builder.Append(item.Name.ToString());
                builder.Append(' ');
                builder.Append("EMPTY");
                builder.Append('>');
                }
            if (inclusions != null)
                foreach (IModelGroupsItem item in inclusions) {
                    builder.AppendLine();
                    builder.Append("<!ELEMENT");
                    builder.Append(' ');
                    builder.Append(item.Name.ToString());
                    builder.Append(' ');
                    builder.Append("EMPTY");
                    builder.Append('>');
                    }
            return DtdSchema.Load(new System.IO.StringReader(builder.ToString()), null, configuration.ElementConfiguration.ElementName);
            }
        }
    }
